package vinnichenko.lab3;

/**Own packages*/
import vinnichenko.lab3.database.*;
import vinnichenko.lab3.exception.*;

/**Java core packages*/
import java.io.*;
import java.sql.*;
import java.util.*;

/**Java extension packages*/
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import org.w3c.dom.*;
import org.xml.sax.*;

import javax.naming.*;
import javax.sql.*;

import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

/**Servlet to display read-only information about a person.
 * @author Igor Vinnichenko
 * @version 1.0
 */
public class PersonInfoServlet extends HttpServlet {
    /**UID*/
    private static final long serialVersionUID = 4L;

    /**Declaration and creation logger.*/
    static Logger logger = Logger.getLogger(PersonInfoServlet.class);

    /**Database object*/
    private EmployeeDB employeeDB;

    /**Servlet initialization method.*/
    public void init()throws ServletException{
        /**Get DAO attribute from servlet context.*/
        EmployeesDAO empDAO = (EmployeesDAO)getServletContext().getAttribute("eDB");

        /**If DAO doesn't exist then throw exception.*/
        if( empDAO == null ){
            throw new UnavailableException("Couldn't get database.");
        }

        /**Create database object and give it to database*/
        employeeDB = new EmployeeDB();
        employeeDB.setDatabase( empDAO );
        logger.info("PersonInfoServlet initialization successful.");
    }

    /**Method called when servlet is near to be destroyed*/
    public void destroy(){
        /**Set database object to null.*/
        employeeDB = null;
        logger.info("PersonInfoServlet destroyed.");
    }

    /**Method to process 'get' request.
     * Get request gets from database information about person and gives it
     * to output.
     * @param request - servlet request.
     * @param response - servlet response.
     * @throws ServletException, IOException.
     */
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException{
        logger.info("PersonInfoServlet doGet ...");

        /**Set content type - text/html*/
        response.setContentType( "text/html" );
        /**Getting writer for output data*/
        PrintWriter out = response.getWriter();  
      
        try{
            /**Get employee number parameter from request.*/
            String empno = request.getParameter( "empno" );

            /**Object that will contain all information and from which we will get XML data.*/
            EmployeeInfo emp = employeeDB.getEmployee( empno );

            /**get a DocumentBuilderFactory for creating
             * a DocumentBuilder (i.e., an XML parser)*/
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            /**Get a DocumentBuilder for building the DOM tree*/
            DocumentBuilder builder = factory.newDocumentBuilder();

            /**Create a new Document (empty DOM tree)*/
            Document messageDocument = builder.newDocument();

            /**Get XML from EmployeeInfo and append to Document*/
            Element employeeElement = emp.getXML( messageDocument );
            messageDocument.appendChild( employeeElement );

            /**Open InputStream for XSL document*/
            InputStream xslStream = 
                            getServletContext().getResourceAsStream( "/readonlyinfo.xsl" );

            /**Transform XML document using XSLT*/
            XMLTransformer.transform( messageDocument, xslStream, out );
        }catch( ParserConfigurationException pcException ){ 
            /**catch XML parser exceptions*/
            logger.error(StackWriter.getFullStackTrace( pcException ));
            getServletContext().setAttribute("javax.servlet.error.exception", (Throwable)pcException );
            throw new ServletException( pcException );
        }catch ( DatabaseConnectException e ){
            logger.error(StackWriter.getFullStackTrace( e ));
            getServletContext().setAttribute("javax.servlet.error.exception", (Throwable)e );
            throw new ServletException( e );
        }catch( EmployeeNotFoundException e ){
            logger.error(StackWriter.getFullStackTrace( e ));
            getServletContext().setAttribute("javax.servlet.error.exception", (Throwable)e );
            throw new ServletException( e );
        }catch ( XSLTTransformingException e ) { 
            logger.error(StackWriter.getFullStackTrace( e ));
            getServletContext().setAttribute("javax.servlet.error.exception", (Throwable)e );
            throw new ServletException( e );
        }

        /**Flush and close output.*/
        out.flush();
        out.close();
    }   
}
